<?php

namespace App\Http\Controllers\Index;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Session;
use App\Http\Service\User\UserService;

use Illuminate\Support\Facades\Redis;

use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

class IndexController extends Controller
{


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 首页
     */
    public function home()
    {
        $where['token'] = Session::get('MEMBER_TOKEN');
        $user = new UserService();
        $data =$user->getUserInfo($where);

        if($data['error_code'] == '0')
        {
            $data = $data['data'];
        }else{
            echo "<script>confirm('{$data['error_message']}')?location.href='/' : history.back() ;</script>";
            exit();
        }

        unset($data['info']['password']);
        unset($data['line']);

//dd($data);
        return view("Home.home")->with('data',$data);
    }


    /**
     * @param Request $request
     * 获取用户账号信息
     */
    public function getAccountInfo(Request $request)
    {
        $where = [];
        $where['token'] = Session::get('MEMBER_TOKEN');
        $user = new UserService();
        $data =$user->getUserInfo($where);

        if($data['error_code'] == '0')
        {
            $data = $data['data'];
        }else{
            echo "<script>confirm('{$data['error_message']}')?location.href='/' : history.back() ;</script>";
            exit();
        }

        unset($data['info']['password']);

//        dd($data);

        return view('Index.index')->with('data',$data);

    }


    public function renewAccount(Request $request)
    {
        $where = [];

        $where = $request->except('_token');
        $where['token'] = Session::get('MEMBER_TOKEN');
        $where['order_id'] = self::createUuid();
//        dd($where);
        $user = new UserService();
        $data =$user->renewAccount($where);

        if($data['error_code'] == '0')
        {
            echo '<script>location.href="/account";alert("账户续费成功！");</script>';
        }else{
            echo "<script>confirm('{$data['error_message']}')?location.href='/account' : history.back() ;</script>";
            exit();
        }
    }
    
    
    

    /**
     * @param Request $request
     * 快捷创建测试账户
     */

    public function QuickOpenTestAccount()
    {
        $where = [];

        $where['username'] = self::randUserName(5);

        $user = new UserService();
        $ret =$user->checkUserName($where);

        if($ret['data']['tag'] != 'success')
        {
            self::QuickOpenTestAccount();
        }
        $where['token'] = Session::get('MEMBER_TOKEN');
        $where['concent_num'] = 1;
        $where['account_type'] = '测试';
        $where['password'] = self::randUserName(3);
        $where['type'] = 1;
        $where['order_id'] = self::createUuid();
        $where['set-meal-type'] = 2;
        $data = $user->addAccount($where);

        return response()->json($data);
    }


    public function QuickOpenPayAccount(Request $request)
    {
        $where = [];
        $where = $request->all();

        $where['username'] = self::randUserName(5);

        $user = new UserService();
        $ret =$user->checkUserName($where);

        if($ret['data']['tag'] != 'success')
        {
            self::QuickOpenTestAccount();
        }
        $where['token'] = Session::get('MEMBER_TOKEN');

        $where['account_type'] = '付费';
        $where['set-meal-type'] =$where['set_meal_type'];
        $where['password'] = self::randUserName(3);
        $where['order_id'] = self::createUuid();

        $data = $user->addAccount($where);
        return response()->json($data);

    }
    
    
    


    /**
     * @param Request $request
     * 获取用户账号列表
     */
    public function getAccountList(Request $request)
    {
        $where['token'] = Session::get('MEMBER_TOKEN');
        $user = new UserService();
        $data = $user->getManageInfo($where);

        $discount = $data['data']['discount'];
        $list = $data['data']['list'];


        return view('Account.account')->with('discount',$discount)->with('list',$list);
    }


    public function getAccountListData(Request $request)
    {
        $where = [];

        $where['start_date'] = '';
        $where['end_date'] = '';
        $where['username'] = '';
        $where['orderByType'] = '';
        $where['orderBy'] = '';

        $where= $request->except('_token');

        if($request->has('page'))
        {
            $where['page_no'] = $request->input('page');
            unset($where['page']);
        }

        foreach($where as $key=>$value)
        {
            if($value =='' || $value == 'undefined')
            {
                unset($where[$key]);
            }
        }

        $where['token'] = Session::get('MEMBER_TOKEN');
        $user = new UserService();
        $data = $user->getAccountList($where);

        return json_encode($data);

    }




    // 获取某一用户在线列表
    public function getBillList(Request $request)
    {
        $where = [];
        $where= $request->except('_token');
        $where['token'] = Session::get('MEMBER_TOKEN');

        $user = new UserService();
        $data = $user->getBillList($where);

        if($data['error_code'] != 0)
        {
            $message =  $data['error_message'];
            echo "<script>confirm('{$message}')?location.href='/' : history.back() ;</script>";
            exit();
        }

        $data = $data['data'];
        return view('Bill.list')->with('data',$data);
    }



    /**
     * @param Request $request
     * 用户账户连接列表
     */
    public function getAccountOnline(Request $request)
    {
        $where = [];
        $where= $request->except('_token');
        $where['token'] = Session::get('MEMBER_TOKEN');

        $user = new UserService();
        $data = $user->getAccountOnline($where);
        if($data['error_code'] == '0')
        {
            $data = $data['data'];
        }else{
            $data = [];
        }
        return view('Account.list')->with('data',$data);
    }

    /**
     * @param Request $request
     * 账号限速
     */
    public function limitSpeed(Request $request)
    {
        $where= $request->except('_token');
        $where['token'] = Session::get('MEMBER_TOKEN');

        $user = new UserService();
        $data = $user->limitSpeed($where);

        if($data['error_code'] == '0')
        {
            echo '<script>location.href="/account";alert("限速成功！");</script>';
        }else{
            echo "<script>confirm('{$data['error_message']}')?location.href='/account' : history.back() ;</script>";
            exit();
        }

    }



    /**
     * @param Request $request
     * 添加账号
     */
    public function addAccount(Request $request)
    {
        $where = [];
        $where= $request->except('_token');
        $where['token']=Session::get('MEMBER_TOKEN');

        if($where['account_type']== '测试')
        {
            unset($where['date']);
            unset($where['date_type']);
            unset($where['account']);
        }else{
            $where['price'] = $where['concent_num'] * $where['date'] *$where['account'];
        }

        $where['order_id'] = self::createUuid();

        $user = new UserService();

        $data = $user->addAccount($where);

        if($data['error_code'] == '0')
        {
            echo '<script>location.href="/account";alert("账号添加成功！");</script>';
        }else{
            echo "<script>confirm('{$data['error_message']}')?location.href='/account' : history.back() ;</script>";
            exit();
        }

    }







    /**
     * @param Request $request
     * @return $this
     * 获取账号 在线信息
     */
    public function getAccountOnlineInfo(Request $request)
    {
        $where = [];
        $where['account_id'] = $request->input('account_id');
        $user = new UserService();
        $data = $user->getAccountOnlineInfo($where);

        if($data['error_code'] == '0')
        {
            $data = $data['data'];
        }else{
            echo "<script>confirm('{$data['error_message']}')?location.href='/account' : history.back() ;</script>";
            exit();
        }

        $data['account_id'] = $where['account_id'];
        return view('Account.online')->with('data',$data);

    }

    /**
     * @param Request $request
     * 禁用用户
     */
    public function forbiddenAccount(Request $request)
    {
        $where  = [];
        $where = $request->all();

        $user = new UserService();
        $data = $user->forbiddenAccount($where);

        return response()->json($data);
    }

    /**
     * @param Request $request
     * 修改账户信息
     */
    public function updateAccount(Request $request)
    {
        $where = [];
        $where= $request->except('_token');

        $user = new UserService();
        $data = $user->updateAccount($where);

        if($data['error_code'] == '0')
        {
            echo '<script>location.href="/account";alert("账号信息修改成功！");</script>';
        }else{
            echo "<script>confirm('{$data['error_message']}')?location.href='/account' : history.back() ;</script>";
            exit();
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     * 删除账户
     */
    public function deleteAccount(Request $request)
    {
        $where = [];

        $where['id']=trim($request->input('id'),',');
        $where['token']=Session::get('MEMBER_TOKEN');

        $user = new UserService();
        $data = $user->deleteAccount($where);
        return response()->json($data);

    }


    /**
     * @param $random_length
     * @return string
     * 生成用户名
     */
    function randUserName($random_length)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $random_string = '';
        for ($i = 0; $i < $random_length; $i++) {
            $random_string .= $chars [mt_rand(0, strlen($chars) - 1)];
        }
        return $random_string;
    }


    //   筛选视图

    public function sort(Request $request)
    {
        $where['token'] = Session::get('MEMBER_TOKEN');
        $user = new UserService();
        $data = $user->getManageInfo($where);

        $discount = $data['data']['discount'];
        $list = $data['data']['list'];


        return view('Sort.sort')->with('discount',$discount)->with('list',$list);

    }


    public function sortlist(Request $request)
    {
        $where = [];

        $where['start_date'] = '';
        $where['end_date'] = '';
        $where['username'] = '';
        $where['orderByType'] = '';
        $where['orderBy'] = '';

        $where= $request->except('_token');

        if($request->has('page'))
        {
            $where['page_no'] = $request->input('page');
            unset($where['page']);
        }

        foreach($where as $key=>$value)
        {
           if($value =='' || $value == 'undefined')
           {
               unset($where[$key]);
           }
        }

        $where['token'] = Session::get('MEMBER_TOKEN');
        $user = new UserService();
        $data = $user->getAccountList($where);

        return json_encode($data);

    }





    //可以指定前缀   生成用户ID
    static function createUuid($prefix = "")
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid  = substr($str,0,8) . '-';
        $uuid .= substr($str,8,4) . '-';
        $uuid .= substr($str,12,4) . '-';
        $uuid .= substr($str,16,4) . '-';
        $uuid .= substr($str,20,12);
        return $prefix . $uuid;
    }




}
